import { Component,ViewChild,ElementRef } from "@angular/core"
import { AlertController,NavController,LoadingController,NavParams,Platform } from "ionic-angular"
import { ImagePicker } from '@ionic-native/image-picker';
import { HttpClient,HttpHeaders } from '@angular/common/http';
import { NativeStorage } from '@ionic-native/native-storage';
import { Camera,CameraOptions } from '@ionic-native/camera';
import { FileTransfer,FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer';
import { PostfeePage } from '../../../pay/postfee/postfee';
import { AppConfig } from '../../../../app/app.config';
import { PostlistPage } from '../../../more/postlist/postlist'
declare var google;
@Component({
    selector: "page-filter",
    templateUrl: "rent.html",
})
export class PostrentPage{
    @ViewChild('map') mapElement:ElementRef;
    alert_sign=false;
    marker:any;
    src = AppConfig.getMainUrl();
    map:any;
    addresslist=[];
    top:any;
    logo:string;
    full_logo:string
    logos=[];
    video:string;
    info = {
        cate:1,
        logo: '',
        logos: '',
        full_logo: '',
        video:'',
        autoorder: 1,
        share: 1,
        type:'',
        address: '',
        living: '',
        bedroom: '',
        bathroom: '',
        area:'',
        area_unit:'1',
        price:'',
        price_unit:'1',
        price_type:'1',
        floor:'',
        total_floor:'',
        deposit:'',
        deposit_unit:'1',
        deposit_save:'-1',
        house_conf:'2',
        house_conf_ids:'',
        renting_starttime:'',
        renting_endtime:'',
        other_price:'',
        other_unit:'1',
        other_description:'',
        owner_name:'',
        owner_email: '',
        owner_tel: '',
        description: '',
        stu_in:0,
        pet_in:0,
        people_in:'1',
        bill:0,
        top_status: '',
        top_starttime: '',
        top_endtime: '',
        is_share_info:1,
        latitude:'',
        longitude:'',
        place_id:'',
    }
    funish_options=[
        {
            id:1,
            ngclass:'iconfont icon-detail_sofa',
            text:'Sofa',
            checked:0,
        },
        {
            id:2,
            ngclass:'iconfont icon-detail_bed',
            text:'Bed',
            checked:0,
        },
        {
            id:3,
            ngclass:'iconfont icon-detail_TV',
            text:'TV',
            checked:0,
        },
        {
            id:4,
            ngclass:'iconfont icon-detail_air',
            text:'Air conditioning',
            checked:0,
        },
        {
            id:5,
            ngclass:'iconfont icon-detail_balcony',
            text:'Balcony',
            checked:0,
        },
        {
            id:6,
            ngclass:'iconfont icon-detail_boiler',
            text:'Boiler',
            checked:0,
        },
        {
            id:7,
            ngclass:'iconfont icon-post_wardrobe',
            text:'Sofa',
            checked:0,
        },
        {
            id:8,
            ngclass:'iconfont icon-detail_refrigerator',
            text:'Refrigerator',
            checked:0,
        },
        {
            id:9,
            ngclass:'iconfont icon-detail_heating',
            text:'Heating',
            checked:0,
        },
        {
            id:10,
            ngclass:'iconfont icon-detail_wash',
            text:'Washing machine',
            checked:0,
        },
        {
            id:11,
            ngclass:'iconfont icon-detail_garden',
            text:'Garden',
            checked:0,
        },
        {
            id:12,
            ngclass:'iconfont icon-detail_parking',
            text:'Parking',
            checked:0,
        },
    ]
    id:string
    loading:any
    pre_price:number;
    limit=1;
    token:string;
    advertising:string;
    constructor(
        private imgPicker:ImagePicker,
        private http:HttpClient,
        private alertCtrl:AlertController,
        private navCtrl:NavController,
        private loadingCtrl:LoadingController,
        private stroge:NativeStorage,
        private transfer:FileTransfer,
        private camera:Camera,
        private navParams:NavParams,
        private platform:Platform
    ){
        this.advertising = './assets/imgs/banner.png'
    }
    delImg(index:number){
        let str = '';
        this.logos = this.logos.splice(index,1)
        this.logos.forEach((ele,i)=>{
            if(str==''){
                str = ele 
            }else{
                str +=','+ele
            }
        })
    }
    imgSelect(){
        if(this.limit < 6){
            this.imgPicker.getPictures({maximumImagesCount:1}).then((results)=>{
                if(!!results.length){
                    this.loadWait();
                    for (var i=0;i<results.length;i++){
                        let fileTransfer: FileTransferObject = this.transfer.create();
                        let options:FileUploadOptions = {
                            fileKey: 'img',
                            chunkedMode: false,
                        }
                        fileTransfer.upload(results[0], AppConfig.getUrl()+'house/upload_img?token='+this.token ,options,true).then((data) => {
                            let response = JSON.parse(data.response) 
                            if(response['code']==101){
                                this.logos.push(response['data']['thumb_img']);
                                if(this.info.logos==""){
                                    this.info.logos = response['data']['thumb_img']
                                }else{
                                    this.info.logos += ','+response['data']['thumb_img']
                                }
                                this.limit++;
                            }else{
                                this.alertb(response['msg'],'');
                            }
                            this.loading.dismiss();
                        }, (err) => {
                            this.alertb('Error!','');
                            this.loading.dismiss();
                        })
                    }
                }
            })
        }else{
            this.alertb('Error','Can only upload up to 5 photos')
        }
        
    }
    logoSelect(sign=true){
        this.imgPicker.getPictures({maximumImagesCount:1}).then((results)=>{
            if(!!results.length){
            this.loadWait();
            for (var i=0;i<results.length;i++){
                let fileTransfer: FileTransferObject = this.transfer.create();
                let options:FileUploadOptions = {
                    fileKey: 'img',
                    chunkedMode: false,
                 }
                fileTransfer.upload(results[0], AppConfig.getUrl()+'house/upload_img?token='+this.token ,options,true).then((data) => {
                    let response = JSON.parse(data.response) 
                    if(response['code']==101){
                        sign?this.logo = AppConfig.getMainUrl()+response['data']['thumb_img']:this.full_logo = AppConfig.getMainUrl()+response['data']['thumb_img']
                        sign?this.info.logo = response['data']['thumb_img']:this.info.full_logo = response['data']['thumb_img']
                    }else{
                        this.alertb(response['msg'],'');
                    }
                    this.loading.dismiss();
                    console.log(data);
                }, (err) => {
                    this.alertb('Error!','');
                    this.loading.dismiss();
                    console.log(err);
                })
                
            }
        }
        })
    }
    chooseVideo(){
        const options: CameraOptions = {
            quality: 50,
            destinationType: this.camera.DestinationType.FILE_URI,
            sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
            mediaType:this.camera.MediaType.VIDEO
        }
        this.camera.getPicture(options).then((VideoUrl) => {
            this.loadWait();
            let fileTransfer: FileTransferObject = this.transfer.create();
            let url = "",options:FileUploadOptions;
            if (this.platform.is('android')) {
                url = 'file:///'+VideoUrl
                options ={
                    fileKey: 'video',
                    fileName:'video.mp4',
                    mimeType:'video/mpeg',
                    headers:new HttpHeaders({ 'Content-Type': 'multipart/form-data' }),
                    chunkedMode: false,
                }
            }else{
                url = VideoUrl
                options ={
                    fileKey: 'video',
                    fileName:'video.moz',
                    mimeType:'video/quicktime',
                    headers:new HttpHeaders({ 'Content-Type': 'multipart/form-data' }),
                    chunkedMode: false,
                }
            }
            fileTransfer.upload(url, AppConfig.getUrl()+'house/upload_vodeo?token='+this.token,options,true).then((data) => {
                let response = JSON.parse(data.response) 
                if(response['code']==101){
                    this.video = AppConfig.getMainUrl()+response['data']['file']
                    this.info.logo = response['data']['file']
                }else{
                    this.alertb(response['msg'],'');
                }
                this.loading.dismiss();
            }, (err) => {
                this.alertb('Error!','');
                this.loading.dismiss();console.log(err);
            })
        }, (err) => {
            // Handle error
        });
      
        
    }
    alertb(title,subTitle){
        let alert = this.alertCtrl.create({
            title: title,
            subTitle: subTitle,
            buttons: ['OK']
        });
        alert.present();
    }
    ionViewDidLoad(){
        this.id = this.navParams.get('id');
        this.stroge.getItem('token').then(token=>{
            this.token = token
            if(this.id){
                this.http.get(AppConfig.getUrl()+'house/info?id='+this.id+'&token='+token).subscribe(res=>{
                    if(res['code']==101){
                        this.info = res['data']
                        this.logo = this.src + res['data']['logo']
                        this.logos = res['data']['logos']
                        this.info.area_unit = this.info.area_unit.toString()
                        this.info.price_unit = this.info.price_unit.toString()
                        this.info.deposit_unit = this.info.deposit_unit.toString()
                        this.info.deposit_save = this.info.deposit_save.toString()
                        this.info.house_conf = this.info.house_conf.toString()
                        this.info.other_unit = this.info.other_unit.toString()
                        if(res['data']['logos']!=[]){
                            res['data']['logos'].forEach(element => {
                                if(this.info.logos==""){
                                    this.info.logos = element
                                }else{
                                    this.info.logos += ','+element
                                }
                            });
                        }
                    }
                })
            }
            this.http.get(AppConfig.getUrl()+'index/setting?token='+token).subscribe((res)=>{
                if(res['code']==101){
                    this.pre_price = res['data']['info_let']
                }
            })
            this.http.get(AppConfig.getUrl()+'user/getInfo?token='+token).subscribe((res)=>{
                if(res['code']==101){
                    this.info.owner_name = res['data']['lastname']
                    this.info.owner_email = res['data']['email']
                    this.info.owner_tel = res['data']['mobile']
                }
            })
        })
        this.stroge.getItem('latlng').then(latlng=>{
            this.loadmap(latlng);
        }).catch(()=>{
            this.loadmap({lat:43.0741904,lng:-88.2801122});
        })
        this.http.get(AppConfig.getUrl()+'Links/index').subscribe((res)=>{
            if(res['code']==101){
                this.advertising = AppConfig.getMainUrl() + res['data'][4]['logo']
            } 
        })
        
    }
    loadmap(latlng){
        this.map = new google.maps.Map(this.mapElement.nativeElement,{
            center:{
                lat:latlng[0]?latlng[0]:43.0741904,
                lng:latlng[0]?latlng[1]:-88.2801122,
            },
            zoom:8,
            disableDefaultUI: true,
        })
        
        this.map.addListener('click',(e)=>{
            if(this.marker){
                this.marker.setPosition(e.latLng)
            }else{
                this.marker = new google.maps.Marker({
                    position: e.latLng,
                    map: this.map
                });
            }
            this.http.get('https://maps.google.cn/maps/api/geocode/json?latlng='+e.latLng.lat()+','+e.latLng.lng()+'&language=EN&key=AIzaSyD-3zV0yAE9iwRXvPm7E-2pgrjYFaVZqrA').subscribe(jsonArray=>{
                if(jsonArray['results'].length>0){
                    for(let i=0;i<jsonArray['results'].length;i++){
                        if(jsonArray['results'][i]['types'][0]=='locality'){
                            this.info.place_id = jsonArray['results'][i].place_id;
                        }
                    }
                }
                this.http.get('https://maps.googleapis.com/maps/api/place/nearbysearch/json?location='+e.latLng.lat()+','+e.latLng.lng()+'&radius=500&key=AIzaSyD-3zV0yAE9iwRXvPm7E-2pgrjYFaVZqrA').subscribe(res=>{
                    this.addresslist = res['results'];
                })
            })
            
        })
    }
    
    loadWait(){
        this.loading = this.loadingCtrl.create({
            content: 'Please wait...'
        });
        this.loading.present();
    }
    submit(){
        if( !this.info.logo ){
            this.alertb('Error','Please upload an image first!')
            return false;
        }
        if( !(this.info.address&&this.info.latitude&&this.info.longitude) ){
            this.alertb('Error','Please select an address!');
            return false;
        }
        if( !this.info.area ){
            this.alertb('Error','Please fill in the building area!');
            return false;
        }
        if( !this.info.price ){
            this.alertb('Error','Please fill in the rent fees!');
            return false;
        }
        if( !this.info.owner_name ){
            this.alertb('Error','Please fill in the name!');
            return false;
        }
        if( !this.info.owner_email ){
            this.alertb('Error','Please fill in the email!');
            return false;
        }
        this.stroge.getItem('token').then((res)=>{
            this.loadWait();
            if(!!this.id){
                this.http.post(AppConfig.getUrl()+'house/edit?id='+this.id+'&token='+res, AppConfig.urlEcode(this.info), { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) }).subscribe( res => {
                    this.loading.dismiss()
                    if(res['code']===101){
                        this.alertb('Edit successed!',res['msg']);
                        this.navCtrl.pop()
                    }else{
                        this.alertb('Error!',res['msg']);
                    }
                })
            }else{
                this.http.post(AppConfig.getUrl()+'house/add?token='+res, AppConfig.urlEcode(this.info), { headers: new HttpHeaders({ 'Content-Type': 'application/x-www-form-urlencoded' }) }).subscribe( res => {
                    this.loading.dismiss()
                    if(res['code']===101){
                        this.alertb('successed!',res['msg']);
                        this.navCtrl.pop()
                        this.navCtrl.push(PostlistPage)
                    }else if(res['code']==203){
                        this.navCtrl.push(PostfeePage,{data:res['data']})
                    }else{
                        this.alertb('Error!',res['msg']);
                    }
                })
            }
        }).catch(()=>{
            this.alertb('Error!','please login first!');
        })
        
    }
    furniture(){
        let res:any;
        this.funish_options.forEach((value,key)=>{
            if(!!value.checked){
                if(!res){
                    res = value.id
                }else{
                    res += ','+value.id
                }
            }
        })
        this.info.house_conf_ids = res;
    }
    
}